package boardgamer.common.client.preference;

import android.content.SharedPreferences;
import android.preference.ListPreference;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

import java.util.EnumSet;
import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author garysoed
 */
public class RegisteredEnumList<V extends Enum<V>>
    extends AbstractRegisteredPreference<V, ListPreference> {

  private final StringConverter<V> stringConverter;
  private final Renderer<V> renderer;

  RegisteredEnumList(String key, ListPreference preference, V defaultValue, Class<V> clazz,
      SharedPreferences sharedPreferences, StringConverter<V> stringConverter,
      Renderer<V> renderer) {
    super(key, preference, defaultValue, sharedPreferences);

    List<String> entryValues = Lists.newArrayList();
    List<String> entries = Lists.newArrayList();
    for (V value : EnumSet.allOf(clazz)) {
      entries.add(renderer.render(value));
      entryValues.add(stringConverter.toString(value));
    }
    
    preference.setEntries(Iterables.toArray(entries, String.class));
    preference.setEntryValues(Iterables.toArray(entryValues, String.class));

    this.stringConverter = checkNotNull(stringConverter, "stringConverter");
    this.renderer = checkNotNull(renderer, "renderer");
  }

  @Override
  protected V getFromSharedPreferences() {
    return stringConverter.valueOf(
        sharedPreferences.getString(key, stringConverter.toString(defaultValue)));
  }

  @Override
  public void setValue(V newValue) {
    preference.setSummary(renderer.render(newValue));
  }
  
  public interface Renderer<T> {
    String render(T object);
  }
}
